import axios from "axios"; // 引入axios
import QS from "qs";
import $router from "@/router";
import user from "../store/modules/user.js";
// import { MessageBox, message, notify } from "element-gui";
import { MessageBox as messageBox } from "element-gui";
axios.defaults.timeout = 60000; // 设置请求失效时间60秒
// 添加请求拦截器
// axios.interceptors.request.use(
//   (config) => {
//     // 在发送请求之前做些什么
//     // 1、判断是否需要登录
//     console.log(`请求【${config.url}】${config.needLogin ? "需要" : "不需要"}登录`);
//     // if (config.needLogin) {
//     //   if (store.state.token) {
//     //     console.log(`【store.state.token】存在 = ${store.state.token}`);
//     //   } else {
//     //     console.warn(`【store.state.token】不存在`);
//     //     // 需要从 localStorage 中重新获取token，获取失败则跳转登录页
//     //   }
//     // }
//     // 2、将token添加入头部
//     // if (store.state.token) {
//     //   // 如果vuex中存储有用户token,就把token传给后端
//     //   config.headers.token = `${store.state.token}`;
//     // }
//     return config;
//   },
//   (error) =>
//     // 对请求错误做些什么
//     Promise.reject(error)
// );
function loginWarningFn() {
  clearInterval(window.setIntervalFlag);
  if (!window.messageBoxFlag) {
    window.messageBoxFlag = true;
    // 返回 410 清除token信息并跳转到登录页面
    messageBox({
      title: "提示",
      type: "warning",
      // customClass: "login-warning-box",
      message: "抱歉通知您,您的账户在别处登录,您被迫下线，如非本人操作请及时修改密码",
      closeOnPressEscape: false,
      closeOnClickModal: false,
      showClose: false,
      showCancelButton: false,
      confirmButtonText: "确定",
      beforeClose: (action, instance, done) => {
        if (action === "confirm") {
          window.name = ""; // 查看视频页面覆盖
          $router.replace({
            path: "/Login"
          });
          done();
        } else {
          done();
        }
        // console.log("user", user);
        user.actions.logOutAfterFn();
        window.messageBoxFlag = null;
      }
    });
  }
}
// 拦截器
axios.interceptors.response.use(
  (response) =>
    // console.log("response", response);
    // if (response.data.code === 511) {
    //   loginWarningFn();
    //   // response.data = { success: true, code: 511, message: "", data: { data: [], pageBean: {}, result: [] } };
    // }
    response,
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          $router.replace({
            path: "/Login"
          });
          break;
        // case 401:
        case 410:
          loginWarningFn();
        // Promise.resolve
        // return Promise.resolve({ success: true, code: 0, message: "", data: { data: [] } }); // 返回接口返回的错误信息
      }
    }
    return Promise.resolve({ success: true, code: 0, message: "", data: { data: [] } }); // 返回接口返回的错误信息
    // return Promise.reject(error.response.data); // 返回接口返回的错误信息
  }
);
// 共用方法提取
async function httpFn(httpType, url, params, headersType = {}) {
  // console.log(axios);
  try {
    let res = await axios[httpType](url, params, headersType);
    // console.log("res", res);
    if (res.starts === 401) {
      location.reload();
    }
    res = res.data;
    // console.log(res);
    return new Promise((resolve, reject) => {
      if (res) {
        resolve(res);
      } else {
        reject(res);
      }
    });
  } catch (err) {
    console.error(err);
  }
}
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export async function get(url, params) {
  const res = await httpFn("get", url, { params });
  return res;
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export async function post(url, params) {
  const res = await httpFn("post", url, QS.stringify(params), {
    headers: {
      "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
    }
  });
  return res;
}
/**
 * postJson方法，对应post请求，json形式的请求头
 * @param {String} url [请求的url地址]
 * @param {JsonStr} params [请求时携带的参数]
 */
export async function postJson(url, params) {
  const res = await httpFn("post", url, params, {
    headers: { "content-type": "application/json;charset=UTF-8" }
  });
  return res;
}
/**
 * postFile方法，对应post请求，上传文件的请求头
 * @param {String} url [请求的url地址]
 * @param {JsonStr} params [请求时携带的参数]
 */
export async function postFile(url, params) {
  const res = await httpFn("post", url, params, {
    headers: { "content-type": "multipart/form-data" }
  });
  return res;
}
/**
 * postJson方法，对应post请求，json形式的请求头
 * @param {String} url [请求的url地址]
 * @param {JsonStr} params [请求时携带的参数]
 */
export async function getBuffer(url, params) {
  const res = await httpFn("post", url, params, {
    headers: { responseType: "arraybuffer" }
  });
  return res;
}
/**
 * del方法，对应delete请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export async function del(url, params) {
  const res = await httpFn(
    "delete",
    url,
    { params },
    { headers: { "content-type": "application/json;charset=UTF-8" } }
  );
  return res;
}
/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export async function put(url, params) {
  const res = await httpFn("put", url, QS.stringify(params), {
    headers: {
      "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
    }
  });
  return res;
}
/**
 * putJson方法，对应put请求,，json形式的请求头
 * @param {String} url [请求的url地址]
 * @param {JsonStr} params [请求时携带的参数]
 */
export async function putJson(url, params) {
  const res = await httpFn("put", url, params, {
    headers: { "content-type": "application/json;charset=UTF-8" }
  });
  return res;
}
/**
 * putJson方法，对应put请求,，json形式的请求头
 * @param {String} url [请求的url地址]
 * @param {JsonStr} params [请求时携带的参数]
 */
export async function patchJson(url, params) {
  const res = await httpFn("patch", url, params, {
    headers: { "content-type": "application/json;charset=UTF-8" }
  });
  return res;
}
/**
 * getData方法，对应type请求,，json形式的请求头
 * @param {String} url [请求的url地址]
 * @param {JsonStr} params [请求时携带的参数]
 */
export async function getData(type, url, params) {
  const res = await httpFn(type, url, params, {
    headers: { "content-type": "application/json;charset=UTF-8" }
  });
  return res;
}
